package com.browsesoft.user;

import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Element;

import com.browsesoft.ManagerGroup;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.htmlcomponent.HTMLTreeModel;
import com.browsesoft.resource.Resource;

public class MainPageTreeModel implements HTMLTreeModel {
	public MainPageTreeModel() {
	}

	/**
	 * 功能树所对应的用户
	 */
	private User user = null;

	/**
	 * 初始化model
	 * 
	 * @throws Exception
	 */
	public void init(HttpServletRequest request) throws Exception {
	}

	/**
	 * 处理用户请求
	 * 
	 * @param request
	 *            客户端请求
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 装载用户的所有功能
		user = (User) request.getSession(false).getAttribute("loginUser");
		user.loadFunctions();
	}

	/**
	 * 取得根结点
	 * 
	 * @return 根结点
	 */
	public Object getRootNode() throws Exception {
		if (user.getRoles().size() > 0) {
			LinkedList v = user.getRootFunctions();
			if (v.size() > 0) {
				Function f = (Function) v.get(0);
				return f.getParent();
			}
		}
		return null;
	}

	/**
	 * 根据结点返回子结点
	 * 
	 * @return 子结点
	 */
	public LinkedList getChildNodes(Object node) throws Exception {
		return user.getChildFunctions((Function) node);
	}

	/**
	 * 根据结点返回结点的名称
	 * 
	 * @return 结点的名称
	 */
	public String getName(Object node) throws Exception {
		return (String) ((Function) node).getAttributes().get("name");
	}

	/**
	 * 根据结点返回结点的id
	 * 
	 * @return 结点的名称
	 */
	public String getID(Object node) throws Exception {
		return ((Function) node).getID();
	}

	/**
	 * 根据id找到结点对象
	 * 
	 * @return 结点对象
	 */
	public Object getObject(String ID) throws Exception {
		FunctionManager manager = (FunctionManager) ManagerGroup
				.getManagerGroup().getManager("function");
		return manager.getObject(ID);
	}

	/**
	 * 根据结点返回结点的链接
	 * 
	 * @return 结点的链接
	 */
	public String getLink(Object node) throws Exception {
		return (String) ((Function) node).getAttributes().get("link");
	}

	/**
	 * 设置模型所对应的组件
	 * 
	 * @param component
	 *            对应的组件
	 */
	public void setComponent(HTMLBasicComponent component) {
	}

	/**
	 * 模型更新页面元素
	 * 
	 * @throws Exception
	 */
	public void updatePageElement(HTMLBasicComponent c) throws Exception {
	}

	/**
	 * 设置链接内容
	 * 
	 * @param nodeLink
	 *            链接'
	 * @param modelNode
	 *            树节点对应的model的节点
	 */
	public void setContextNode(Element nodeLink, Object modelNode)
			throws Exception {
	}

	/**
	 * 判断是否有子
	 */
	public boolean hasChilds(Object obj) {
		Resource res = (Resource) obj;
		return res.getChildren().hasNext();
	}

	/**
	 * 得到节点对应的图标
	 * 
	 * @param node
	 *            节点
	 * @return 图标
	 */
	public String getIcon(Object node) {
		String icon = (String) ((Resource) node).getAttributes().get("f_icon");
		if (icon == null) {
			icon = "fc_default";
		}
		return icon;
	}
}
